//
//  UICodeVerifyViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/18/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UICodeVerifyViewCtrl.h"
#import "UIRegProfileViewCtrl.h"
#import "RegViewController.h"
@interface UICodeVerifyViewCtrl ()

@end

@implementation UICodeVerifyViewCtrl {
  NSInteger _nActRegBodyId;
  NSString* _sBodyEmail;
  NSString* _sUserName;
  
  
  UILabel* _lblCodeVerifyTips;
    
  UITextField* _txtVerifyCode;
  UIButton* _btnCodeVerify;
  UIActivityIndicatorView* _actView;
    
  UILabel* _lblNoRecvMsgTips;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.5];
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
    
    [self initViewCtrls:W hgt:H];
    _actView = nil;
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _nActRegBodyId = pApp.m_bodyInfo.m_nBodyId;
  _sBodyEmail = pApp.m_bodyInfo.sEmail;
  _sUserName = [NSString stringWithFormat:@"%@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
  
  //pApp.m_nLoginBodyId = -1;
  [pApp clearRegData];
    UIImageView *iView = [[UIImageView alloc] initWithFrame:self.view.frame];
    iView.contentMode = UIViewContentModeScaleAspectFill;
    iView.image = [UIImage imageNamed:@"ic-reg2"];
    [self.view insertSubview:iView atIndex:0];
}

- (void) initViewCtrls:(CGFloat) W hgt:(CGFloat)H
{
    UILabel *tipLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 79, W - 20, 20)];
    tipLable.textAlignment = NSTextAlignmentCenter;
    tipLable.textColor = [UIColor whiteColor];
    tipLable.font = Bold(16);
    tipLable.text = [NSLocalizedString(@"Verification", nil) uppercaseString];
    [self.view addSubview:tipLable];
    
    BOOL bIpad = H > 1000;
    BOOL bWider = W > 320;
    CGFloat xPos = 15;
//    CGFloat xPos = bIpad? 60:20;
    CGFloat yPos = bWider? 80: 60;
    
    _lblCodeVerifyTips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(tipLable.frame) + 15, W - xPos * 2, 60)];
    _lblCodeVerifyTips.font = Regular(16);
    _lblCodeVerifyTips.textColor = [UIColor whiteColor];
    _lblCodeVerifyTips.textAlignment = NSTextAlignmentLeft;
    _lblCodeVerifyTips.lineBreakMode = NSLineBreakByWordWrapping;
    _lblCodeVerifyTips.numberOfLines = 0;
    _lblCodeVerifyTips.text = NSLocalizedString(@"A verification code has been sent to the provided e-mail address. Please enter the verification code below", nil);
    [self.view addSubview:_lblCodeVerifyTips];
    
    UILabel *codeLable = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_lblCodeVerifyTips.frame) + 15, W - xPos * 2, 20)];
    codeLable.textColor = [UIColor whiteColor];
    codeLable.font = Regular(16);
    codeLable.text = NSLocalizedString(@"Verification Code", nil);
    [self.view addSubview:codeLable];
    
    yPos += 40;
    _txtVerifyCode = [[UITextField alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(codeLable.frame) + 2, W - xPos * 2, H / 16.7)];
    _txtVerifyCode.textColor = [UIColor whiteColor];
    _txtVerifyCode.backgroundColor = [UIColor clearColor];
    _txtVerifyCode.font = [UIFont systemFontOfSize:bIpad?17:14];
    _txtVerifyCode.borderStyle = UITextBorderStyleRoundedRect;
    _txtVerifyCode.layer.cornerRadius = 6;
    _txtVerifyCode.layer.borderColor = [UIColor whiteColor].CGColor;
    _txtVerifyCode.layer.borderWidth = 1.0f;
    _txtVerifyCode.keyboardType = UIKeyboardTypeNumberPad;
    //_txtVerifyCode.placeholder = @"Verificarion code"; //NSLocalizedString(@"Name", nil);
    [self.view addSubview: _txtVerifyCode];
    
    yPos += 45;
    _btnCodeVerify = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnCodeVerify.frame = CGRectMake(xPos, H - (H / 16.7) - 20, W - xPos * 2, H / 16.7);
//    [_btnCodeVerify setBackgroundImage:[UIImage imageNamed:@"btn-verify.png"] forState:UIControlStateNormal];
    
    [_btnCodeVerify addTarget:self action:@selector(onVerifyCode:) forControlEvents:UIControlEventTouchUpInside];
    _btnCodeVerify.backgroundColor = [UIColor colorWithRed:0.84 green:0.13 blue:0.46 alpha:1.00];
    _btnCodeVerify.layer.cornerRadius = 8;
    _btnCodeVerify.tintColor = [UIColor whiteColor];
    [_btnCodeVerify setTitle:NSLocalizedString(@"SignUp", nil)/*@"SIGN UP"*/ forState:UIControlStateNormal];
    _btnCodeVerify.titleLabel.font = Regular(16);
    //_btnRegSubmit.backgroundColor = [UIColor lightGrayColor];
    //_btnRegTag.layer.masksToBounds = YES;
    //_btnRegSubmit.layer.cornerRadius = 4;
    //[_btnRegSubmit setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_btnCodeVerify];
    
    yPos += 40;
  _lblNoRecvMsgTips = [[UILabel alloc] initWithFrame:CGRectMake(xPos, CGRectGetMaxY(_txtVerifyCode.frame) + 20, W - xPos * 2, 90)];
  _lblNoRecvMsgTips.font = Regular(16);
  _lblNoRecvMsgTips.textColor = [UIColor whiteColor];
  _lblNoRecvMsgTips.textAlignment = NSTextAlignmentLeft;
  _lblNoRecvMsgTips.lineBreakMode = NSLineBreakByWordWrapping;
  _lblNoRecvMsgTips.numberOfLines = 0;
  _lblNoRecvMsgTips.text = NSLocalizedString(@"If you didn't receive a verification code, please select Back and make sure your information is correct", nil);
  _lblNoRecvMsgTips.hidden = NO;
  [self.view addSubview:_lblNoRecvMsgTips];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  //_lblMsg.text = @"No enough memory!";
  AudioServicesPlaySystemSound(1112);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) onVerifyCode:(id)sender
{
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    LoginBodyInfo * bodyInfo = pApp.m_bodyInfo;
    NSInteger nBodyId = _nActRegBodyId; //bodyInfo.m_nBodyId;
    if(nBodyId <= 0 && pApp.m_nLoginBodyId <= 0) {
        _lblNoRecvMsgTips.text = @"Sorry, an error happed, please try again later.";
        AudioServicesPlaySystemSound(1109);
        return;
    }
    if(nBodyId <= 0) {
        //nBodyId = pApp.m_nLoginBodyId;
        _lblNoRecvMsgTips.text = @"Sorry, BodyId exception";
        AudioServicesPlaySystemSound(1109);
        return;
    }
    
    if(_actView == nil) {
        CGRect rt = _btnCodeVerify.frame;
        rt.origin.x += rt.size.width - rt.size.height * 2;
        rt.size.width = rt.size.height;
        _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
        _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        _actView.hidesWhenStopped = YES;
        [self.view addSubview:_actView];
    }
    _btnCodeVerify.hidden = YES;
    [_actView startAnimating];
    
    // 创建一个描述订单信息的JSON数据
    NSString* sActCode = _txtVerifyCode.text;
    NSDictionary *regInfo = @{
                              @"BodyId" : [NSString stringWithFormat:@"%d", (int)nBodyId],
                              @"UserId" : @"0",
                              @"ActCode" : sActCode,
                              @"Email": _sBodyEmail,
                              @"UserName": _sUserName
                              };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:@"Mob" data:regInfo];
    
    
    // 6.发送请求
    //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil || connectionError)
            return;
        
        _btnCodeVerify.hidden = NO;
        NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        sRecv = [sRecv substringFromIndex:1];
        if([sRecv hasPrefix:@"Failed"]) {
            sRecv = [sRecv substringWithRange: NSMakeRange(0, sRecv.length-1)];
            _lblNoRecvMsgTips.text = [NSString stringWithFormat:@"%@! Verification code not right.", sRecv];
            [_actView stopAnimating];
            AudioServicesPlaySystemSound(1109);
            return;
        }
        
        if(bodyInfo.m_nBodyId <= 0)
            bodyInfo.m_nBodyId = nBodyId;
        
        //[pApp saveRegBodyInfo:nBodyId email:sEmail first:sFirst last:sLast tagId:sTagId];
        
        
//        UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        UIRegProfileViewCtrl* vcProf = [mainStory instantiateViewControllerWithIdentifier:@"userProfViewCtrl"];
//        [pApp.m_pNavController pushViewController:vcProf animated:YES];
        RegViewController * vcProf = [[RegViewController alloc] init];
        [self.navigationController pushViewController:vcProf animated:YES];
        
        //check if forget pswd & no act
        if([bodyInfo.m_sTagId isEqualToString:@"*"] && bodyInfo.sFirst == nil && bodyInfo.sLast == nil) {
            [pApp getUserGoalData:YES];
        }
        
//        [self performSelector:@selector(hideDatePickerCol:) withObject:vcProf afterDelay:0.5 ];
        [_actView stopAnimating];
    }];
    
}

- (void) hideDatePickerCol:(UIRegProfileViewCtrl*) vcProf {
  [vcProf hideBirthDayDateCol];
}

@end
